package com.juneng.utils.wechat;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.juneng.utils.wechat.PaypreIdRequestHandler;
import com.juneng.utils.wechat.WXUtil;
import com.juneng.utils.wechat.WeChatConfig;
import com.juneng.utils.wechat.XMLUtil;
import com.juneng.utils.wxpay.WxPayAppConfigutil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ResourceUtils;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;

public class WXPayUtil {

    public static Map<String, Object> getPay(HttpServletRequest request, HttpServletResponse response, String internalOrder, String total_amount, String body) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        // 获取生成预支付订单的请求类
        PaypreIdRequestHandler prepayReqHandler = new PaypreIdRequestHandler(request, response);
        int total_fee = (int) (Float.valueOf(total_amount) * 100);
        prepayReqHandler.setParameter("appid", WeChatConfig.APP_ID);
        prepayReqHandler.setParameter("body", body);
        prepayReqHandler.setParameter("mch_id", WeChatConfig.MCH_ID);
        String nonce_str = WXUtil.getNonceStr();
        prepayReqHandler.setParameter("nonce_str", nonce_str);
        prepayReqHandler.setParameter("notify_url", WeChatConfig.NOTIFY_URL);
        prepayReqHandler.setParameter("out_trade_no", internalOrder);
        prepayReqHandler.setParameter("spbill_create_ip", request.getRemoteAddr());
        String timestamp = WXUtil.getTimeStamp();
        prepayReqHandler.setParameter("time_start", timestamp);
        prepayReqHandler.setParameter("total_fee", String.valueOf(total_fee));
        prepayReqHandler.setParameter("trade_type", "APP");
        /**
         * 注意签名（sign）的生成方式，具体见官方文档（传参都要参与生成签名，且参数名按照字典序排序，最后接上APP_KEY,转化成大写）
         */
        prepayReqHandler.setParameter("sign", prepayReqHandler.createMD5Sign());
        prepayReqHandler.setGateUrl(WeChatConfig.GATEURL);
        String result = prepayReqHandler.sendPrepay();
        // 若获取prepayid成功，将相关信息返回客户端
        String prepayid = "";
        Map<String, String> resultMap = XMLUtil.doXMLParse(result);
        if (resultMap.containsKey("prepay_id")) {
            prepayid = resultMap.get("prepay_id");
        }
        if (prepayid != null && !prepayid.equals("")) {
            PaypreIdRequestHandler prepayReqHandlers = new PaypreIdRequestHandler(request, response);
            prepayReqHandlers.setParameter("appid", resultMap.get("appid"));
            prepayReqHandlers.setParameter("partnerid", resultMap.get("mch_id"));
            prepayReqHandlers.setParameter("prepayid", prepayid);
            prepayReqHandlers.setParameter("appid", resultMap.get("appid"));
            prepayReqHandlers.setParameter("package", "Sign=WXPay");
            prepayReqHandlers.setParameter("noncestr", resultMap.get("nonce_str"));
            prepayReqHandlers.setParameter("timestamp", timestamp);
            String sign = prepayReqHandlers.createMD5Sign();
            prepayReqHandlers.setParameter("sign", sign);
            map.put("prepayid", prepayid);
            map.put("returncode", resultMap.get("return_code"));
            map.put("returnmsg", resultMap.get("return_msg"));
            map.put("appid", resultMap.get("appid"));
            map.put("partnerid", resultMap.get("mch_id"));
            map.put("noncestr", resultMap.get("nonce_str"));
            map.put("sign", sign);
            map.put("tradetype", resultMap.get("trade_type"));
            map.put("packages", "Sign=WXPay");
            map.put("timestamp", timestamp);  //等于请求prepayId时的time_start
        } else {
            map.put("code", 1);
            map.put("info", "获取prepayid失败");
        }
        return map;
    }

    /**
     * 微信退款
     * @param request
     * @param response
     * @param transactionId  微信支付订单号
     * @param outTradeNo  商户订单号
     * @param outRefundNo 商户退款号
     * @param totalFee   订单金额
     * @param refundFee 退款金额
     * @return
     * @throws Exception
     */
    public static Map<String, String> getReimburse(HttpServletRequest request, HttpServletResponse response,String transactionId, String outTradeNo, String outRefundNo, String totalFee, String refundFee, String body ) throws Exception {
      //  WxPayAppConfigutil wxPayAppConfigutil = new WxPayAppConfigutil();
        WxPayAppConfigutil instance = WxPayAppConfigutil.getInstance();
        System.out.println(instance);
        WXPay wxpay = new WXPay(instance, WXPayConstants.SignType.MD5, false);
        Map<String, String> data = new HashMap<>();
        data.put("appid", WeChatConfig.APP_ID);
        data.put("mch_id", WeChatConfig.MCH_ID);
        data.put("nonce_str", WXUtil.getNonceStr());
        data.put("sign_type", "MD5");
//        data.put("notify_url", MyWxPayUtil.refund_notify_url);
        //插入订单信息 confirmDelivery
        data.put("out_trade_no", outTradeNo); //微信订单号
        data.put("out_refund_no", outRefundNo); //商户退款单号
   //     data.put("total_fee", );//支付金额，微信支付提交的金额是不能带小数点的，且是以分为单位,这边需要转成字符串类型，否则后面的签名会失败
   //     data.put("refund_fee", );//退款总金额,订单总金额,单位为分,只能为整数
        int total_fee = (int) (Float.valueOf(totalFee) * 100);
        int refund_fee = (int) (Float.valueOf(refundFee) * 100);
        data.put("total_fee", String.valueOf(total_fee)); //订单总金额
        data.put("refund_fee",String.valueOf(refund_fee)); //退款金额
        //生成签名
        String sign = com.github.wxpay.sdk.WXPayUtil.generateSignature(data, WeChatConfig.APP_KEY);
        data.put("sign", sign);
        Map<String, String> returnMap = wxpay.refund(data);
        System.out.println(returnMap);
        System.out.println(returnMap.get("return_code"));
        return returnMap;
    }

    public static void main(String[] args) throws Exception {
//        WxPayAppConfigutil instance = WxPayAppConfigutil.getInstance();
//        System.out.println(instance);
//        WXPay wxpay = new WXPay(instance, WXPayConstants.SignType.MD5, false);
//        Map<String, String> data = new HashMap<>();
//        data.put("appid", WeChatConfig.APP_ID);
//        data.put("mch_id", WeChatConfig.MCH_ID);
//        data.put("nonce_str", WXUtil.getNonceStr());
//        data.put("sign_type", "MD5");
//        data.put("out_trade_no","2021080901888465414");//微信订单号
//        data.put("out_refund_no", "2021080901850154616");//商户退款单号
//        data.put("total_fee","1");//支付金额，微信支付提交的金额是不能带小数点的，且是以分为单位,这边需要转成字符串类型，否则后面的签名会失败
//        data.put("refund_fee","1");//退款总金额,订单总金额,单位为分,只能为整数
//        //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口
//        String sign = com.github.wxpay.sdk.WXPayUtil.generateSignature(data, WeChatConfig.APP_KEY);
//        data.put("sign", sign);
//        Map<String, String> returnMap = wxpay.refund(data);
//        System.out.println(returnMap);
        String s = String.valueOf(Double.parseDouble("0.01") * 100);
        System.out.println(s);
        int total_fee = (int) (Float.valueOf("0.01") * 100);
        System.out.println(total_fee);
    }
}
